/*
 * Copyright 2016 Lianjia
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.an.proj.contacts.net.service.retrofit.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.an.proj.contacts.config.LogUtil;

/**
 * 创建时间: 2016/08/09 17:25 <br>
 * 作者: fuchaoyang <br>
 * 描述: 请求头拦截器
 */
public abstract class HeaderInterceptor implements Interceptor {
  private final HashMap<String, String> mHeaders;

  public HeaderInterceptor() {
    mHeaders = new HashMap<>();
  }

  @Override public Response intercept(Chain chain) throws IOException {

    // 拦截器Interceptor 对于每个请求都会处理一次
    LogUtil.d("intercept", "HeaderInterceptor");
    Request.Builder newBuilder = chain.request().newBuilder();
    initHeaders();

    if (mHeaders.size() > 0) {
      Set<Map.Entry<String, String>> entries = mHeaders.entrySet();

      for (Map.Entry<String, String> entry : entries) {
        //if (entry.getValue() == null) continue;
        newBuilder.addHeader(entry.getKey(), entry.getValue());
      }
    }

    Request request = newBuilder.build();

    return chain.proceed(request);
  }

  /**
   * 集合中的'key-value'将被用于添加至特定的网络请求的请求头中
   */
  public HeaderInterceptor addHead(String name, String value) {
    if (value != null) mHeaders.put(name, value);
    return this;
  }

  /**
   * 初始化header
   * {@link #addHead(String, String)}
   */
  public abstract void initHeaders();
}
